<script setup lang="ts">
import Header from '@/components/Header.vue'
import Menu from '@/components/Menu.vue'
import MyBox from '@/components/MyBox.vue'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { Query, Operate } from '@/api'
import { useMessage } from '@/hooks/useMessage'
import RatioChart from '@/views/KB-Main/components/RatioChart.vue'
import YieldChart from '@/views/KB-Docking/components/YieldChart.vue'
import SeamlessList from '@/views/KB-Docking/components/SeamlessList.vue'
import ProductionTrend from '@/views/KB-Main/components/ProductionTrend.vue'
import GaugeChart from '@/views/KB-Main/components/GaugeChart.vue'
const currentEnv = import.meta.env.DEV
const baseURL = window.location.origin
const { query } = useRoute()
type filedInfo = {
  cmbInfo:any,
  listDescr: string,
  isEdit:string,
  isShow:string,
  label:string,
  type:string,
  width:string,
  value:string
}
type chart = {
  legendList: string[]
  timeList: string[]
  planList: number[]
  targetList: number[]
  actualList: number[]
  max: string
  min: string
}
type chartInfo = {
  list: listInfo[]
}
type listInfo = {
  value: number
  name: string
}
type deviceInfo = {
  Capa: string,
  DeviceNo: string,
  IP: string,
  ImageName: string,
  Name: string,
  Number: string,
  Status: string,
  YR: string
}
const currentIndex = ref(false)
const currentItem = ref({
  Capa:'',
  DeviceNo:'',
  IP:'',
  ImageName:'',
  Name:'',
  Number:'',
  Status:'',
  YR:''
})

const tableData = ref([])
//看板标题
const title = ref('')
const lineListInfo = ref({
  Shift: '',
  Line: '',
})
const lineFieldList = ref<filedInfo[]>([])
//折线图
const yieldChartInfo = ref<chart>({
  legendList: [],
  timeList: [],
  planList: [],
  targetList: [],
  actualList: [],
  max: '',
  min: ''
})

const yieldChartInfo5 = ref<chart>({
  legendList: [],
  timeList: [],
  targetList: [],
  actualList: [],
  max: '',
  min: ''
})
const deviceList = ref([])
const deviceField = ref([])
const maintenanceList = ref<filedInfo[]>([])
const statusInfoList = ref<filedInfo[]>([])
const achieveRateList = ref<filedInfo[]>([])

//设备状态
const statusList = ref([
  {
    label: '离线',
    color: '#BFBFBF'
  },
  {
    label: '待机',
    color: '#F4EA2A'
  },
  {
    label: '运行',
    color: '#1AFA29'
  },
  {
    label: '故障',
    color: '#D81E06'
  },
  {
    label: '急停',
    color: '#E98F36'
  }
])
const statusMap = {
  0: statusList.value[0], // 离线
  1: statusList.value[1], // 待机
  2: statusList.value[2], // 运行
  3: statusList.value[3], // 故障
  4: statusList.value[4] // 急停
}
const FPYStatusMap = {
  0: statusList.value[3], // 红色
  1: statusList.value[4], // 橙色
  2: statusList.value[2] // 绿色
}

//设备图片
const imageList = ref<deviceInfo[]>([])

//刷新周期
const flushTimer = ref()

const achieveRate = ref({
  A_Qty: '',
  Per: '',
  T_Qty:''
})

const capaList = ref<filedInfo[]>([])
const deviceCapaList = ref<filedInfo[]>([])

//设备状态统计
const rationChartInfo1 = ref<chartInfo>({
  list: []
})
const rationChartInfo2 = ref<chartInfo>({
  list: []
})
const rationChartInfo3 = ref<chartInfo>({
  list: []
})
//线别
const line = ref('')
const lineList = ref()
//站别
const station = ref('')
const stationList = ref()

//获取表格和图表数据
const getKBInfo = async () => {
  const res = (await Query({
    inputStr: `GroupName=${query.groupName};$;JobType=${query.jobType};$;OperType=GetKBInfo;$;Key=Station;$;Line=${line.value};$;Station=${station.value}`
  })) as any
  if (res.code !== 200) {
    message.error(res.msg)
    return
  }
  const {
    maintenanceInfo,
    lineInfo,
    statusInfo,
    achieveRateInfo,
    deviceInfo,
    capaInfo,
  } = res.data

  rationChartInfo1.value.list =
    statusInfo.map((item: any) => {
      return {
        value: item.Qty,
        name: item.Name,
        Per: item.Per,
        TTLQty: item.TTLQty
      }
    }) || []


  rationChartInfo2.value.list = [
    {
      value: maintenanceInfo[0].ToBeQty,
      name: '待保',
      ...maintenanceInfo[0]
    },
    {
      value: maintenanceInfo[0].NGQty,
      name: '过保',
      ...maintenanceInfo[0]
    },
    {
      value: maintenanceInfo[0].OKQty,
      name: '正常',
      ...maintenanceInfo[0]
    },
    {
      value: maintenanceInfo[0].TTLQty,
      name: '总数',
      ...maintenanceInfo[0]
    }
  ]
  achieveRate.value = achieveRateInfo[0] || {}
  rationChartInfo3.value.list = [
    {
      value: parseFloat(achieveRate.value.Per.replace(/%/g, '')),
      name: '',
      ...achieveRate.value
    },
  ]
  yieldChartInfo.value.timeList = capaInfo.map((item: any) => item.TimeNode)
  yieldChartInfo.value.actualList = capaInfo.map((item: any) => Number(item.A_Qty))
  yieldChartInfo.value.planList = capaInfo.map((item: any) => Number(item.T_Qty))

  lineListInfo.value = lineInfo[0]
  imageList.value = deviceInfo || []
}
//切换站别
const changeStation = async () => {
  // 先关闭定时器再重新启动刷新周期
  stopTimer()
  //选择站别之后，开始循环获取数据GetKBInfo
  startTimer()
}

const message = useMessage()
//获取页面信息
const getPageInfo = async () => {
  const res = (await Query({
    inputStr: `GroupName=${query.groupName};$;JobType=${query.jobType};$;OperType=Getpage`
  })) as any
  if (res.code !== 200) {
    message.error(res.msg)
    return
  }
  const {
    achieveRateFieldInfo,
    maintenanceFieldInfo,
    statusFieldInfo,
    deviceCapaFieldInfo,
    deviceFieldInfo,
    lineInfo,
    lineFieldInfo,
    capaFieldInfo
  } = res.data
  capaList.value = capaFieldInfo || []
  deviceCapaList.value = deviceFieldInfo.filter((item: any) => ['Seq', 'ImageName', 'Status','Number','DeviceNo'].indexOf(item.value) == -1) || []
  lineList.value = lineInfo || []
  statusInfoList.value = statusFieldInfo || []
  maintenanceList.value = maintenanceFieldInfo || []
  achieveRateList.value = achieveRateFieldInfo || []

  flushTimer.value = lineInfo.length && lineInfo[0].RefCT
  title.value = lineInfo[0].Name
  lineFieldList.value = lineFieldInfo || []
  // deviceField.value = mtrlFieldInfo.filter((item: any) => item.isShow == 'true') || []
  // mtrlList.value = mtrlFieldInfo.filter((item: any) => ['DeviceNo', 'Model', 'SKU'].includes(item.value))
}

const queryDeviceDetail = async (id: any) => {
  const res = (await Operate({
    inputStr: `GroupName=${query.groupName};$;JobType=${query.jobType};$;OperType=Operate;$;Oper=GetDeviceInfo`,
    jsonData: { DeviceNo: id }
  })) as any
  if (res.code !== 200) {
    message.error(res.msg)
    return
  }
  const { deviceCapaInfo, mtrlInfo } = res.data
  deviceList.value = mtrlInfo || []
  yieldChartInfo5.value.timeList = deviceCapaInfo.map((item: any) => item.TimeNode)
  yieldChartInfo5.value.actualList = deviceCapaInfo.map((item: any) => item.Value)
}

// 1.循环过程中，重新选择【线别】，关闭循环，选定【站别】后重新开始
// 2.循环过程中，重新选择【站别】，关闭循环并开始新循环

// 定义状态
const isRunning = ref(false)
const timerId = ref<number | null>(null)

// 开始定时器
const startTimer = async () => {
  if (isRunning.value) return // 防止重复启动

  isRunning.value = true
  console.log('定时器启动')

  // 立即执行一次
  await getKBInfo()

  // 设置定时器，每3分钟执行一次 (3分钟 = 3*60*1000 = 180000毫秒)
  const timer = flushTimer.value ? flushTimer.value * 1000 : 10000
  console.log(timer)
  timerId.value = window.setInterval(getKBInfo, timer)
}

// 停止定时器
const stopTimer = () => {
  if (timerId.value) {
    window.clearInterval(timerId.value)
    timerId.value = null
    isRunning.value = false
    console.log('定时器已停止')
  }
}

// 组件卸载前清理定时器
onBeforeUnmount(() => {
  stopTimer()
})

const showOverlay = (item: any) => {
  currentIndex.value = true
  currentItem.value = item
  queryDeviceDetail(item.DeviceNo)
}

const setBgColor = (status: string) => {
 switch (status) {
  case '0':
    return 'background: rgba(191, 191, 191,.7);'
  case '1':
    return 'background: rgba(244, 234, 42,1);'
  case '2':
    return 'background: rgba(26, 250, 41,.7);'
  case '3':
    return 'background: rgba(216, 30, 6,.7);'
  case '4':
    return 'background: rgba(233, 143,1);'
 }
}
const getImageUrl = (list: any) => {
  if(currentEnv){
    return new URL(`/src/assets/deviceImages/${list.ImageName}.png`, import.meta.url).href
  } else {
    return `${baseURL}/deviceImages/${list.ImageName ? list.ImageName : '1-8'}.png`
  }
}

onMounted(async () => {
  await getPageInfo()
  // getKBInfo()
  await startTimer()
})
</script>
<template>
  <div class="w-full overflow-hidden my-page">
    <Header :title="title" />
    <section class="board-content">
      <el-row :gutter="20">
        <el-col :span="24">
          <MyBox title="" style="width: 100%; margin: 10px 0;">
            <template v-slot:main>
              <div class="flex items-center">
                <p v-if="lineFieldList.length > 0 " class="run-info" v-for="(i,index) in lineFieldList" :key="index">
                  <label>{{ i.label}}：</label>
                  <span>{{ lineListInfo[i.value]}}</span>
                </p>
              </div>
            </template>
          </MyBox>
        </el-col>
        <el-col :span="5">
          <MyBox v-if="statusInfoList.length > 0" :title="statusInfoList[0].listDescr">
            <template v-slot:main>
              <RatioChart :data="rationChartInfo1" />
            </template>
          </MyBox>
        </el-col>
        <el-col :span="5">
          <MyBox v-if="maintenanceList.length > 0" :title="maintenanceList[0].listDescr">
            <template v-slot:main>
              <RatioChart :data="rationChartInfo2" />
            </template>
          </MyBox>
        </el-col>
        <el-col :span="5">
          <MyBox v-if="achieveRateList.length > 0" :title="achieveRateList[0].listDescr">
            <template v-slot:main>
              <GaugeChart :data="rationChartInfo3" />
              <div class="flex items-center">
                <div style="text-align: center" class="run-info">
                  <label>计划:</label>
                  <span>{{ achieveRate.T_Qty }}</span>
                </div>
                <div style="text-align: center" class="run-info">
                  <label>实际:</label>
                  <span>{{ achieveRate.A_Qty }}</span>
                </div>
              </div>
            </template>
          </MyBox>
        </el-col>
        <el-col :span="9">
          <MyBox v-if="capaList.length > 0" :title="capaList[0].listDescr">
            <template v-slot:main>
              <ProductionTrend :data="yieldChartInfo" />
            </template>
          </MyBox>
        </el-col>
      </el-row>
      <div style="margin-top: 10px">
        <MyBox title="设备信息">
          <template v-slot:extra>
            <div class="flex items-center justify-between status-info">
              <p v-for="(item, index) in statusList" :key="index" class="flex items-center">
                <span class="status-color" :style="{ background: item.color }"></span>
                <span class="status-text">{{ item.label }}</span>
              </p>
            </div>
          </template>
          <template v-slot:main>
            <div class="image-list flex flex-wrap">
              <div class="device-box" style="width: 33.3%" v-for="(item, index) in imageList" :key="index">
                <el-row :gutter="20">
                  <el-col :span="10">
                    <div
                      class="image-card items-center"
                    >
                      <img style="width:80px;height: 140px" :src="getImageUrl(item)" alt="Image" />
                      <p class="device-text">{{ item.Number }}</p>
                      <p :style="setBgColor(item.Status)" class="device-line"></p>
                    </div>
                  </el-col>
                  <el-col :span="14">
                    <div class="text-box" v-for="(i,index) in deviceCapaList" :key="index">
                      <p class="text-item">
                        <label>{{ i.label}}：</label>
                        <span>{{ item[i.value]}}</span>
                      </p>
                    </div>

                  </el-col>
                </el-row>

              </div>

            </div>

          </template>
        </MyBox>

      </div>
    </section>
    <Menu />
  </div>
</template>
<style lang="less" scoped>
.large-switch.is-checked {
  :deep(.el-switch__core) {
    .el-switch__action {
      left: calc(100% - 34px) !important;
    }
  }
}
.large-switch {
  :deep(.el-switch__core) {
    height: 36px;
    min-width: 80px;
    border-radius: 20px;
    .el-switch__action {
      width: 34px;
      height: 34px;
    }
    &::after {
      width: 34px;
      height: 34px;
    }
  }

  :deep(.el-switch__inner) {
    font-size: 16px;
  }
}
.container-scroll {
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE/Edge */
}
.container-scroll::-webkit-scrollbar {
  display: none; /* Chrome/Safari */
}
:deep(.custom-btn) {
  font-size: 20px;
}
:deep(.el-button--large) {
  font-size: 20px;
}

.row {
  margin: 15px auto;
}
.extra {
  position: absolute;
  right: 30px;
  top: 10px;
  font-size: 22px;
  color: #8fe1ff;
  .select-box {
    margin-right: 20px;
  }
  p {
    padding-left: 10px;
    &:before {
      display: inline-block;
      content: '';
      width: 18px;
      height: 18px;
      margin-right: 10px;
      background: #00b8a9;
      border-radius: 2px;
    }
    &:first-child {
      &::before {
        background: #f7c873;
        border-radius: 50%;
      }
    }
  }
}
.text-box {
  .text-item{
    padding: 3px;
    font-size: 18px;
  }
}
.other-info {
  color: #8fe1ff;
  font-size: 24px;
  margin-top: 20px;
  .flex {
    width: 98%;
    margin: 0 auto;
  }
}
.el-select-dropdown__item {
  font-size: 18px;
}

.status-info {
  p {
    margin-left: 26px;
  }
  position: absolute;
  right: 28px;
  top: 15px;
  .status-color {
    display: inline-block;
    width: 16px;
    height: 16px;
    margin-right: 8px;
  }
  .status-text {
    font-size: 20px;
    color: #8fe1ff;
  }
}
.device-box{
  border:1px solid #00aeff;
  padding: 15px;
}
.image-list {
  width: 100%;
  margin: 20px 0 0 0;
}
.image-card {
  position: relative;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25);
  cursor: pointer;
  height: 147px;
  margin-top:10px;
  img {
    position: absolute;
    top: 50%;
    left: 70%;
    transform: translate(-50%, -50%);
    z-index: 9;
    //box-shadow: 0 2px 10px rgba(0, 174, 255, 0.3);
  }
  //&:hover .overlay {
  //  opacity: 1;
  //  z-index: 10000;
  //  .arrow {
  //    opacity: 1;
  //  }
  //}
  .device-text {
    text-align: center;
    font-size: 24px;
    margin-bottom: 10px;
    position: absolute;
    top: 50%;
    left: 20%;
    transform: translate(-50%, -50%);
    color: #fff;
    font-weight: bold;
  }
  .device-line {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 35px;
    border-radius: 5px;
  }
}

.run-info {
  margin-left: 10px;
  margin-right: 20px;
  -webkit-flex: 1;
  label {
    color: #fff;
    //margin-right: 15px;
    font-size: 24px;
  }
  span {
    color: #00f2f1;
    font-size: 24px;
  }
  .my-input-number {
    width: 138px;
    height: 36px;
  }
  :deep(.my-input-number .el-input__wrapper) {
    height: 36px;
  }
  :deep(.my-input-number .el-input-number__decrease) {
    background: inherit;
    color: #00aeff;
    font-size: 16px;
    font-weight: 700;
    border-right: 1px solid #00aeff;
  }
  :deep(.my-input-number .el-input-number__increase) {
    background: inherit;
    color: #00aeff;
    font-size: 16px;
    font-weight: 700;
    border-left: 1px solid #00aeff;
  }
}
.yield-list {
  background: rgba(18, 155, 255, 0.2);
  padding: 5px 0;
  height: 40px;
  .yield-item {
    width: 100%;
  }
  .yield-item:not(:last-child) {
    &::after {
      display: block;
      content: '';
      width: 2px;
      height: 24px;
      background: url('@/assets/wo-line.png') no-repeat center center;
      position: absolute;
      top: 4px;
      right: 0;
    }
  }
  .label {
    font-size: 18px;
    color: #fff;
    text-align: center;
  }
  .value {
    font-size: 18px;
    color: #00f2f1;
  }
}
.err-list {
  display: flex;
  overflow-x: auto;
  height: 140px;
  flex-wrap: nowrap;
  /* 左对齐 */
  justify-content: flex-start;
  /* 移除默认内边距 */
  .image-card {
    flex-shrink: 0;
    width: 50px;
    height: 140px;
    .err-img {
      height: 117px;
      position: relative;
    }
    .err-text {
      color: #409eff;
      font-weight: bold;
      text-align: center;
    }
  }
}
</style>
